package com.thenie.service.impl;

import com.thenie.mapper.UserMapper;
import com.thenie.pojo.Employee;
import com.thenie.pojo.User;
import com.thenie.service.UserService;
import com.thenie.utils.PasswordUtil;
import com.thenie.utils.SystemConstant;
import com.thenie.vo.UserVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service()
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    /**
     * 注册用户
     * @param user
     * @return
     */
    public int RegisterUser(User user) {
        //设置盐值
        String salt = UUID.randomUUID().toString().replace(",", "");
        user.setSalt(salt);
        //设置加密后的密码
        user.setPassword(PasswordUtil.md5(user.getPassword(), salt, SystemConstant.PASSWORD_COUNT));
        //设置注册时间
        user.setCreateDate(new Date());
        return userMapper.insertUser(user);
    }
    /**
     * 查询用户根据用户名
     * @param loginName
     * @return
     */
    public User findUserByLoginName(String loginName){
        return userMapper.findUserByLoginName(loginName);
    }

    /**
     * 用户登陆
     * @param loginName
     * @param password
     * @return
     */
    public User login(String loginName, String password) {
        //根据用户名查找用户信息
        User user = userMapper.findUserByLoginName(loginName);
        if (user!=null){
            //获取用户的盐值
            String salt=user.getSalt();
            //对用户输入的密码加密
            String newPassword = PasswordUtil.md5(password, salt, SystemConstant.PASSWORD_COUNT);
            //进行比对
            if (newPassword.equals(user.getPassword())){//相等
                return user;
            }
        }
        return null;
    }

    public List<User> findUserList(UserVo userVo) {
        return userMapper.findUserList(userVo);
    }

    public int resetPwd(String id) {
        //盐值
        String salt = UUID.randomUUID().toString().replace("-", "");
        //密码
        String loginPwd = PasswordUtil.md5(SystemConstant.DEFAULT_LOGIN_PWD, salt, SystemConstant.PASSWORD_COUNT);
        User user = new User();
        user.setId(id);
        user.setSalt(salt);
        user.setPassword(loginPwd);
        return userMapper.resetPwd(user);
    }

    public int deleteUserById(String id) {
        return userMapper.deleteUserById(id);
    }

    public int update(User user) {
        return userMapper.update(user);
    }
}
